package com.mycompany.app.common.ajax.autocompleter.action;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.Iterator;
import java.util.List;

import com.mycompany.app.common.ajax.autocompleter.dao.ICountryDao;
import com.mycompany.app.common.ajax.autocompleter.domain.Country;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionSupport;

@SuppressWarnings("serial")
public class CountryAutoCompleterAction extends ActionSupport {

    private String typeValue;

    private ICountryDao countryDao;

    private InputStream inputStream;

    public InputStream getInputStream() {

        return inputStream;
    }

    public String getTypeValue() {

        return typeValue;
    }

    public void setTypeValue(String typeValue) {

        this.typeValue = typeValue;
    }

    public void setCountryDao(ICountryDao countryDao) {

        this.countryDao = countryDao;
    }

    public String getCountryHint() {

        if (typeValue != null && typeValue.length() > 0) {
            List<Country> list = countryDao.queryCountry(typeValue
                    .toLowerCase());
            StringBuilder sb = new StringBuilder();
            if (list != null && list.size() > 0) {
                Iterator<Country> iterator = list.iterator();
                while (iterator.hasNext()) {
                    Country c = iterator.next();
                    sb.append("<li onclick=\"fill('").append(c.getValue())
                            .append("');\">").append(c.getValue()).append(
                                    "</li>");
                    // <li onClick="fill('Afghanistan');">Afghanistan</li>
                }
            }
            inputStream = new ByteArrayInputStream(sb.toString().getBytes());
        } else {
            inputStream = new ByteArrayInputStream(new String(
                    "ERROR: There was a problem with the query").getBytes());
        }

        return Action.SUCCESS;
    }

}
